package com.isoft.controller;

import com.isoft.common.Result;
import com.isoft.entity.User;
import com.isoft.mapper.UserMapper;
import com.isoft.model.MyResponseData;
import com.isoft.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;


@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @RequestMapping("/login")
    public MyResponseData login( @RequestBody User user, HttpSession session) {
        MyResponseData responseData = new MyResponseData();
        System.out.println(user);

        // 获取会话ID作为键
        redisTemplate.opsForValue().set("verifyCode", user.getVerifyCode());
        if (!user.getVerifyCode().equalsIgnoreCase((String) redisTemplate.opsForValue().get("verifyCode"))) {
            responseData.setErrorCode(2);
            responseData.setMsg("验证码错误");
           return responseData;
        }
        user = userService.login(user);
        if (user == null) {
            responseData.setErrorCode(1);
            responseData.setMsg("登录失败");
        } else {
            responseData.setErrorCode(0);
            responseData.setMsg("登录成功");
            responseData.setObject(user);
        }
        System.out.println(responseData);
        return responseData;
    }

    @GetMapping("/get info/{username}")
    public User getUserById(@PathVariable String username) {

        User havePermission=userMapper.permission(username);
        return havePermission;
    }

    @RequestMapping("/register")
    public Result Register (@RequestBody User user){
        User existingUser = userMapper.register(user);
        if(existingUser != null){
            return Result.error("1","注册失败！已存在用户");
        }
        userMapper.insert(user);
        return Result.success();
    }





}
